<?php

namespace app\app\controller;

use app\app\model\ProjectGGKModel;
use app\app\model\ProjectLZModel;
use app\app\model\ProjectMeetingModel;
use app\app\model\ProjectModel;
use app\app\model\RandModel;
use app\app\model\SysDictDataModel;
use app\BaseController;
use app\Request;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Filesystem;

class ProjectMeetting extends BaseController
{

    public function index(Request $request)
    {
        $data = $request->param();
        $start_time = "2021-12-07 00:00:00";
        $end_time = "2021-12-15 23:59:59";
        $where = " b.lz_time BETWEEN  '" . $start_time . "'  AND '" . $end_time . "'";

        if (isset($data['user_name'])) $where .= " AND b.user_name  LIKE '%" . $data['user_name'] . "%'";
        $list = ProjectMeetingModel::alias('a')->field('b.user_name,count(a.id) as total')
            ->leftjoin('t_project_lz b', 'b.id = a.project_lz_id')
            ->where($where)->group('b.user_name')->select()->toarray();

        $total = array_sum(array_map(function ($val) {
            return $val['total'];
        }, $list));
        $res = array(
            'total' => $total,
            'list' => $list
        );
        $this->success('success', $res);
    }


    public function list(Request $request)
    {
        $data = $request->param();
        $page_size = input('pageSize', '20');

        $where = "1=1";
        if (isset($data['start_time'])) $where .= " AND a.meeting_time BETWEEN  '" . $data['start_time'] . "'  AND '" . $data['end_time'] . "'";
        if (isset($data['user_name'])) $where .= " AND a.user_name  = '" . $data['user_name'] . "'";
        $list = ProjectMeetingModel::alias('a')->field('a.*,b.project_name,c.project_name as main_project_name')
            ->leftjoin('t_project b', 'b.id = a.project_id')
            ->leftjoin('t_project c', 'b.link_project_id = c.id')
            ->where($where)->paginate($page_size);
        $this->success('success', $list);

    }


    public function details()
    {
        $id = input('id');
        $list = ProjectMeetingModel::alias('a')
            ->field('a.*,b.file_path as meeting_file_path,c.file_path as meeting_av_path,d.file_path as meeting_audio_path,f.file_path as meetting_papers_path,e.project_name')
            ->leftJoin('sys_file_info b', 'a.meeting_file_id = b.file_id')
            ->leftJoin('sys_file_info c', 'a.meeting_av_id = c.file_id')
            ->leftJoin('sys_file_info d', 'a.meeting_audio_id = d.file_id')
            ->leftJoin('t_project e', 'e.id = a.project_id')
            ->leftJoin('sys_file_info f', 'a.meetting_papers_id = f.file_id')
            ->find($id);
        $list['meeting_file_path'] = str_replace('\\', '/', $list['meeting_file_path']);
        $list['meeting_av_path'] = str_replace('\\', '/', $list['meeting_av_path']);
        $list['meeting_audio_path'] = str_replace('\\', '/', $list['meeting_audio_path']);

        $gkk = Db::table('t_project_gkk')
            ->where('id', 'in', $list['project_manage_id'])
            ->field(['id', 'ggk_id'])
            ->select();
        $gkk_id = array_column($gkk->toArray(), 'ggk_id');

        $gkk_type = Db::table('t_project_gkk_type')
            ->where('id', 'in', $gkk_id)
            ->field(['id', 'nick_name'])
            ->select();
        $gkk_name = array_column($gkk_type->toArray(), 'nick_name');

        $gkk_name = array_map(function ($v) {
            return substr($v, 3);
        }, $gkk_name);

        $gkk_name = implode(',', $gkk_name);

        $list['gkk_name'] = $gkk_name;

        $this->success('success', $list);
    }


    public function add(Request $request)
    {
        $data = $request->param();
        $data['id'] = RandModel::randId();
        if (isset($data['project_manage_id'])) {
            $project_manage_id_arr = explode(',', $data['project_manage_id']);
            $where[] = ['id', 'IN', $project_manage_id_arr];
            $project_manage_list = ProjectGGKModel::where($where)->where('project_id', $data['project_id'])->select();
            foreach ($project_manage_list as $key => $value) {
                $update['state'] = '已完成';
                $update['finsh_time'] = date('Y-m-d H:i:s', time());;
                ProjectGGKModel::where('id', $value['id'])->update($update);
            }
        }
        ProjectMeetingModel::create($data);
        $this->success('success');

    }


    public function dictData()
    {
        $dict_type = input('dict_type');
        $list = SysDictDataModel::field('dict_code,dict_label,dict_value')->where('dict_type', $dict_type)->select();
        $this->success('success', $list);
    }

    public function check()
    {
        $data = $this->request->param();
        $where[] = ['project_id', '=', $data['project_id']];
        $where[] = ['user_id', '=', $data['user_id']];
        $start_time = $data['lz_date'] . ' 00:00:00';
        $end_time = $data['lz_date'] . ' 23:59:59';
        $where[] = ['lz_time', 'BETWEEN', [$start_time, $end_time]];
        $info = ProjectLZModel::where($where)->select();
        $msg = '未履职';
        if (count($info) > 0) {
            $msg = '已履职';
        }
        $this->success('success', $msg);
    }

    /**
     * 查询会议项目列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function listGroup()
    {
        $name = input('name/s', '');

        $start_time = date('Y-01-01 00:00:00', time());
        $end_time = date('Y-12-31 23:59:59', time());
        $where[] = ['b.tc_time', '>=', $start_time];
        $where[] = ['b.kg_time', '<=', $end_time];
        if ($name) {
            $where[] = ['b.project_name|c.project_name', 'like', '%' . $name . '%'];
        }
        $project_meeting = ProjectMeetingModel::alias('a')
            ->leftJoin('t_project b', 'a.project_id = b.id')
            ->leftJoin('t_project c', 'b.link_project_id = c.id')
            ->where($where)
            ->group('b.id')
            ->field('b.id,b.link_project_id,b.is_parent')
            ->select();

        $project_id_array = array_column($project_meeting->toArray(), null, 'id');
        $project_id_array = array_keys($project_id_array);

        $result = [];
        foreach ($project_meeting as $v) {
            if ($v['is_parent'] == 0) {
                $result[$v['id']] = $v;
                continue;
            }

            $result[$v['link_project_id']]['children'][$v['id']]['children'][] = $v;
        }

        $project_id_array = array_merge($project_id_array, array_keys($result));

        $project = ProjectModel::where('id', 'in', $project_id_array)
            ->field('id, project_name')
            ->select();
        $project = array_column($project->toArray(), null, 'id');

        $result = $this->getProject($result, $project);

        $this->success('success', $result);
    }

    /**
     * 整理项目组列表
     * @param $project_meeting
     * @param $project
     * @return array
     */
    private function getProject($project_meeting, $project)
    {
        foreach ($project_meeting as $k => &$v) {
            $tmp = $v['children'];
            if (isset($project[$k])) {
                $v = $project[$k];
                $v['children'] = $this->getProject($tmp ?: [], $project);

                if (isset($v['children'][0]['link_project_id'])) {
                    unset($v['children']);
                }
            }
        }

        return array_values($project_meeting);
    }

    /**
     * 查询指定项目id下的会议列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function meetingList()
    {
        $id = input('id/s');
        if (!$id) $this->error('请传入id');
        $page_size = input('pageSize', '20');
        $meeting = ProjectMeetingModel::where('project_id', $id)
            ->paginate($page_size);
        if (empty($meeting)) $this->error('未找到符合条件的会议');

        $this->success('success', $meeting);
    }

    /**
     * 修改会议内容
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit()
    {
        $data = $this->request->param();
        if (!$data['id']) $this->error('请传入id');
        $meeting = ProjectMeetingModel::where('id', $data['id'])->find();
        if (empty($meeting)) $this->error('会议不存在');
        $meeting->save($data);
        $this->success('success');
    }


    /**
     *删除会议内容
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function del()
    {
        $id = input('id','');
        if (!$id) $this->error('请传入id');
        $meeting = ProjectMeetingModel::where('id', $id)->find();
        if (empty($meeting)) $this->error('会议不存在');
//        if($meeting['project_manage_id']){
//
//        }
        ProjectMeetingModel::where('id', $id)->delete();

        $this->success('success');
    }



    /**
     * 上传会议附件
     * @return void
     */
    public function upload()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'meeting', $file['file']);

        $this->success('success', ['file_link' => '/storage/' . $file_name]);
    }
}
